/**
 * 查询群组列表
 */
function queryGroupList() {
    $.ajax({
        type: 'GET',
        url: "/service/authorize/group/all",
        headers: {
            Authorization: JwtTokenUtils.getBearerHeader()
        },
        success: function (data) {
            console.log(data);
            for (let i = 0; i < data.length; i++) {
                let group = data[i];

                let groupPanelDiv = $(".group-component .templates .group-panel").clone();
                groupPanelDiv.attr("group-id", group.id);
                groupPanelDiv.css("display", "block");
                groupPanelDiv.find(".panel-title").text(group.name);
                groupPanelDiv.find(".id-value").text(group.id);
                groupPanelDiv.find(".name-value").text(group.name);
                groupPanelDiv.find(".description-value").text(group.description);

                groupPanelDiv.find(".edit-button").click(function () {

                    let editGroupPanel = $(".group-component .templates .edit-group-panel").clone();
                    editGroupPanel.attr("group-id", group.id);
                    editGroupPanel.find(".panel-title").text("Modify Group");
                    editGroupPanel.find(".name-value").val(group.name);
                    editGroupPanel.find(".description-value").val(group.description);

                    editGroupPanel.find(".save-group-button").click(function () {
                        updateGroup(editGroupPanel);
                    });

                    editGroupPanel.find(".cancel-group-button").click(function () {
                        editGroupPanel.remove();
                        groupPanelDiv.css("display", "block");
                    });

                    editGroupPanel.insertBefore($(this).parents(".group-panel"));
                    groupPanelDiv.css("display", "none");
                });

                groupPanelDiv.find(".delete-button").click(function () {
                    PromptWindowUtils.showDeletePrompt("Are you sure you want to delete this group?", function () {
                        $.ajax({
                            type: "DELETE",
                            contentType: "application/json;charset=utf-8",
                            url: "/service/authorize/group/delete/" + group.id,
                            dataType: "json",
                            headers: {
                                token: localStorage.getItem("token")
                            },
                            success: function () {
                                $(".group-component .group-list").empty();
                                queryGroupList();
                                PromptWindowUtils.hideDeletePrompt();
                            }
                        });
                    });
                });

                groupPanelDiv.find(".role-list-wrap .role-list-show-button").click(function () {
                    if ($(this).hasClass("open")) {
                        $(this).removeClass("open");
                        groupPanelDiv.find(".role-list").removeClass("expansion");
                    } else if (groupPanelDiv.find(".role-list").hasClass("queried")) {
                        $(this).addClass("open");
                        groupPanelDiv.find(".role-list").addClass("expansion");
                    } else {
                        queryRoleList(groupPanelDiv);
                    }
                });

                groupPanelDiv.find(".role-list-wrap .add-role-button").click(function () {
                    groupPanelDiv.find(".add-role-panel").addClass("show");

                    groupPanelDiv.find(".add-role-panel .add-existing-role-tab").click(function () {
                        groupPanelDiv.find(".add-role-panel .add-existing-role").addClass("active").addClass("in");
                        groupPanelDiv.find(".add-role-panel .add-new-role").removeClass("active").removeClass("in");
                    });

                    groupPanelDiv.find(".add-role-panel .add-new-role-tab").click(function () {
                        groupPanelDiv.find(".add-role-panel .add-new-role").addClass("active").addClass("in");
                        groupPanelDiv.find(".add-role-panel .add-existing-role").removeClass("active").removeClass("in");
                    });

                    groupPanelDiv.find(".add-role-panel .search-button").click(function () {
                        searchRoles(groupPanelDiv.find(".add-role-panel"));
                    });
                    groupPanelDiv.find(".add-role-panel .search-role-input").keyup(function (event) {
                        if (event.keyCode == "13") {
                            searchRoles(groupPanelDiv.find(".add-role-panel"));
                        }
                    });
                    groupPanelDiv.find(".add-role-panel .ok-button").click(function () {
                        addRole(groupPanelDiv);
                    });
                    groupPanelDiv.find(".add-role-panel .reset-button").click(function () {
                        groupPanelDiv.find(".add-role-panel input").val("");
                        groupPanelDiv.find(".add-role-panel textarea").val("");
                        groupPanelDiv.find(".add-role-panel .search-role-list").empty();
                    });
                    groupPanelDiv.find(".add-role-panel .close-button").click(function () {
                        groupPanelDiv.find(".add-role-panel").removeClass("show");
                    });
                });

                groupPanelDiv.find(".user-list-wrap .user-list-show-button").click(function () {
                    if ($(this).hasClass("open")) {
                        $(this).removeClass("open");
                        groupPanelDiv.find(".user-list").removeClass("expansion");
                    } else if (groupPanelDiv.find(".user-list").hasClass("queried")) {
                        $(this).addClass("open");
                        groupPanelDiv.find(".user-list").addClass("expansion");
                    } else {
                        queryUserList(groupPanelDiv);
                    }
                });

                groupPanelDiv.find(".user-list-wrap .add-user-button").click(function () {
                    groupPanelDiv.find(".add-user-panel").addClass("show");
                });


                groupPanelDiv.find(".add-user-panel .add-existing-user-tab").click(function () {
                    groupPanelDiv.find(".add-user-panel .add-existing-user").addClass("active").addClass("in");
                    groupPanelDiv.find(".add-user-panel .add-new-user").removeClass("active").removeClass("in");
                });

                groupPanelDiv.find(".add-user-panel .add-new-user-tab").click(function () {
                    groupPanelDiv.find(".add-user-panel .add-new-user").addClass("active").addClass("in");
                    groupPanelDiv.find(".add-user-panel .add-existing-user").removeClass("active").removeClass("in");
                });

                groupPanelDiv.find(".add-user-panel .search-button").click(function () {
                    searchUsers(groupPanelDiv.find(".add-user-panel"));
                });
                groupPanelDiv.find(".add-user-panel .search-user-input").keyup(function (event) {
                    if (event.keyCode == "13") {
                        searchUsers(groupPanelDiv.find(".add-user-panel"));
                    }
                });
                groupPanelDiv.find(".add-user-panel .ok-button").click(function () {
                    addUser(groupPanelDiv);
                });
                groupPanelDiv.find(".add-user-panel .reset-button").click(function () {
                    groupPanelDiv.find(".add-user-panel input").val("");
                    groupPanelDiv.find(".add-user-panel .search-user-list").empty();
                });
                groupPanelDiv.find(".add-user-panel .close-button").click(function () {
                    groupPanelDiv.find(".add-user-panel").removeClass("show");
                });


                $(".group-component .group-list").append(groupPanelDiv);
            }
        }
    });
}

/**
 * 搜索角色
 * @param addRolePanel
 */
function searchRoles(addRolePanel) {
    let searchText = addRolePanel.find(".search-role-input").val();
    $.ajax({
        type: 'GET',
        url: "/service/authorize/role/findRolesByNameLike",
        headers: {
            Authorization: JwtTokenUtils.getBearerHeader()
        },
        data: {
            name: searchText
        },
        success: function (data) {
            addRolePanel.find(".search-role-list").empty();
            for (let i = 0; i < data.length; i++) {
                let role = data[i];
                let searchRolePanel = $(".group-component .templates .search-role-panel").clone();
                searchRolePanel.find(".search-role-id").attr("value", role.id);
                searchRolePanel.find(".role-name-div").text(role.name);
                searchRolePanel.find(".role-description-div").text(role.description);
                addRolePanel.find(".search-role-list").append(searchRolePanel);
            }
        }
    });
}

/**
 * 搜索用户
 * @param addUserPanel
 */
function searchUsers(addUserPanel) {
    let searchText = addUserPanel.find(".search-user-input").val();
    $.ajax({
        type: 'GET',
        url: "/service/authorize/user/findUserByName",
        headers: {
            Authorization: JwtTokenUtils.getBearerHeader()
        },
        data: {
            name: searchText
        },
        success: function (data) {
            addUserPanel.find(".search-user-list").empty();
            for (let i = 0; i < data.length; i++) {
                let user = data[i];
                let searchUserPanel = $(".group-component .templates .search-user-panel").clone();
                searchUserPanel.find(".search-user-id").attr("value", user.id);
                searchUserPanel.find(".username-div").text(user.username);
                searchUserPanel.find(".name-div").text(user.name);
                addUserPanel.find(".search-user-list").append(searchUserPanel);
            }
        }
    });
}

/**
 * 添加角色
 * @param groupPanelDiv
 */
function addRole(groupPanelDiv) {
    let groupId = groupPanelDiv.attr("group-id");
    if (groupPanelDiv.find(".add-existing-role-tab").hasClass("active")) {
        let roleId = groupPanelDiv.find("input[name=search-role-id]:checked").val();
        $.ajax({
            type: "POST",
            url: "/service/authorize/group/assignExistingRole",
            headers: {
                Authorization: JwtTokenUtils.getBearerHeader()
            },
            data: {
                groupId: groupId,
                roleId: roleId
            },
            success: function () {
                queryRoleList(groupPanelDiv);
            }
        });
    } else {
        let roleName = groupPanelDiv.find(".add-new-role .name-value").val();
        let roleDescription = groupPanelDiv.find(".add-new-role .description-value-textarea").val();
        $.ajax({
            type: "POST",
            contentType: "application/json;charset=utf-8",
            url: "/service/authorize/group/addNewRole",
            headers: {
                Authorization: JwtTokenUtils.getBearerHeader()
            },
            data: JSON.stringify({
                groupId: groupId,
                name: roleName,
                description: roleDescription
            }),
            success: function () {
                queryRoleList(groupPanelDiv);
            }
        });
    }
}

/**
 * 从群组关联角色中删除一个角色
 * @param groupPanelDiv
 * @param rolePanel
 */
function deleteRole(groupPanelDiv, rolePanel) {
    let groupId = groupPanelDiv.attr("group-id");
    let roleId = rolePanel.attr("role-id");
    $.ajax({
        type: "DELETE",
        url: "/service/authorize/group/dismissRole",
        headers: {
            Authorization: JwtTokenUtils.getBearerHeader()
        },
        data: {
            groupId: groupId,
            roleId: roleId
        },
        success: function () {
            queryRoleList(groupPanelDiv);
            PromptWindowUtils.hideDeletePrompt();
        }
    });
}

/**
 * 添加用户
 * @param groupPanelDiv
 */
function addUser(groupPanelDiv) {
    let groupId = groupPanelDiv.attr("group-id");
    if (groupPanelDiv.find(".add-existing-user-tab").hasClass("active")) {
        let userId = groupPanelDiv.find("input[name=search-user-id]:checked").val();
        $.ajax({
            type: "POST",
            url: "/service/authorize/group/addExistingUser",
            headers: {
                Authorization: JwtTokenUtils.getBearerHeader()
            },
            data: {
                groupId: groupId,
                userId: userId
            },
            success: function () {
                queryUserList(groupPanelDiv);
            }
        });
    } else {
        let username = groupPanelDiv.find(".add-new-user-panel .username-value").val();
        let name = groupPanelDiv.find(".add-new-user-panel .name-value").val();
        $.ajax({
            type: "POST",
            contentType: "application/json;charset=utf-8",
            url: "/service/authorize/group/addNewUser",
            headers: {
                Authorization: JwtTokenUtils.getBearerHeader()
            },
            data: JSON.stringify({
                groupId: groupId,
                username: username,
                name: name
            }),
            success: function () {
                queryUserList(groupPanelDiv);
            }
        });
    }
}

/**
 * 从群组中删除一个用户
 * @param groupPanelDiv
 * @param userPanel
 */
function deleteUser(groupPanelDiv, userPanel) {
    let groupId = groupPanelDiv.attr("group-id");
    let userId = userPanel.attr("user-id");
    $.ajax({
        type: "DELETE",
        url: "/service/authorize/group/removeUser",
        headers: {
            Authorization: JwtTokenUtils.getBearerHeader()
        },
        data: {
            groupId: groupId,
            userId: userId
        },
        success: function () {
            queryUserList(groupPanelDiv);
            PromptWindowUtils.hideDeletePrompt();
        }
    });
}

/**
 * 查询角色列表
 * @param groupPanelDiv
 */
function queryRoleList(groupPanelDiv) {
    let groupId = groupPanelDiv.attr("group-id");
    $.ajax({
        type: "GET",
        url: "/service/authorize/role/findRolesByGroupId/" + groupId,
        headers: {
            Authorization: JwtTokenUtils.getBearerHeader()
        },
        success: function (data) {
            groupPanelDiv.find(".role-list").empty();
            groupPanelDiv.find(".role-list").addClass("expansion");
            if (!groupPanelDiv.find(".role-list").hasClass("queried")) {
                groupPanelDiv.find(".role-list").addClass("queried");
            }
            groupPanelDiv.find(".role-list-show-button").addClass("open");
            for (let i = 0; i < data.length; i++) {
                let role = data[i];
                let rolePanel = $(".templates .role-panel").clone();
                rolePanel.attr("role-id", role.id);
                rolePanel.find(".role-id-div").text(role.id);
                rolePanel.find(".role-name-div").text(role.name);
                rolePanel.find(".role-description-div").text(role.description);
                rolePanel.find(".delete-role-button").click(function () {
                    PromptWindowUtils.showDeletePrompt("Are you sure you want to delete this role?", function () {
                        deleteRole(groupPanelDiv, rolePanel);
                    });
                });
                groupPanelDiv.find(".role-list").append(rolePanel);
            }
        }
    });
}

/**
 * 查询用户列表
 * @param groupPanelDiv
 */
function queryUserList(groupPanelDiv) {
    let groupId = groupPanelDiv.attr("group-id");
    $.ajax({
        type: "GET",
        url: "/service/authorize/user/findUsersByGroupId/" + groupId,
        headers: {
            Authorization: JwtTokenUtils.getBearerHeader()
        },
        success: function (data) {
            groupPanelDiv.find(".user-list").empty();
            groupPanelDiv.find(".user-list").addClass("expansion");
            if (!groupPanelDiv.find(".user-list").hasClass("queried")) {
                groupPanelDiv.find(".user-list").addClass("queried");
            }
            groupPanelDiv.find(".user-list-show-button").addClass("open");
            for (let i = 0; i < data.length; i++) {
                let user = data[i];
                let userPanel = $(".templates .user-panel").clone();
                userPanel.attr("user-id", user.id);
                userPanel.find(".user-id-div").text(user.id);
                userPanel.find(".username-div").text(user.username);
                userPanel.find(".name-div").text(user.name);
                userPanel.find(".delete-user-button").click(function () {
                    PromptWindowUtils.showDeletePrompt("Are you sure you want to delete this user?", function () {
                        deleteUser(groupPanelDiv, userPanel);
                    });
                });
                groupPanelDiv.find(".user-list").append(userPanel);
            }
        }
    });
}

/**
 * 添加群组
 * @param addGroupPanel
 */
function addGroup(addGroupPanel) {
    let requestData = {};
    requestData.name = addGroupPanel.find(".name-value").val();
    requestData.description = addGroupPanel.find(".description-value").val();

    $.ajax({
        type: 'POST',
        url: "/service/authorize/group/add",
        contentType: "application/json;charset=UTF-8",
        headers: {
            Authorization: JwtTokenUtils.getBearerHeader()
        },
        data: JSON.stringify(requestData),
        success: function () {
            addGroupPanel.remove();
            $(".group-component .add-new-panel").removeClass("disable");
            $(".group-component .group-list").empty();
            queryGroupList();
        }
    });
}

/**
 * 修改群组
 * @param editGroupPanel
 */
function updateGroup(editGroupPanel) {
    let requestData = {};
    requestData.id = editGroupPanel.attr("group-id");
    requestData.name = editGroupPanel.find(".name-value").val();
    requestData.description = editGroupPanel.find(".description-value").val();

    $.ajax({
        type: 'PUT',
        url: "/service/authorize/group/update",
        contentType: "application/json;charset=UTF-8",
        headers: {
            token: localStorage.getItem("token")
        },
        data: JSON.stringify(requestData),
        success: function () {
            $(".group-component .group-list").empty();
            queryGroupList();
        }
    });
}

/**
 * 添加按钮点击事件处理
 * 添加新微服务div显示
 */
function addNewHandle() {
    if ($(".group-component .add-new-panel").hasClass("disable")) {
        return;
    }

    let addGroupPanel = $(".group-component .templates .edit-group-panel").clone();
    addGroupPanel.css("margin-bottom", "0");
    addGroupPanel.find(".panel-title").text("Add Group");
    addGroupPanel.find(".save-group-button").click(function () {
        addGroup(addGroupPanel);
    });
    addGroupPanel.find(".cancel-group-button").click(function () {
        addGroupPanel.remove();
        $(".group-component .add-new-panel").removeClass("disable");
    });
    $(".add-group-div").append(addGroupPanel);
    $(".group-component .add-new-panel").addClass("disable");
}

/**
 * 页面启动完成事件
 *
 * 1.查询微服务列表
 *
 *
 */
$(document).ready(function () {
    queryGroupList();
});